// noinspection HttpUrlsUsage

import React, {useEffect, useState} from "react";
import {useAsyncList} from "@react-stately/data";
import ShareService from "@/app/service/shareService";
import copy from 'copy-to-clipboard';
import {
    Avatar,
    Button,
    Card,
    Chip, Code,
    Spinner, Switch,
    Table,
    TableBody,
    TableCell,
    TableColumn,
    TableHeader,
    TableRow, Tooltip, useDisclosure
} from "@nextui-org/react";
import {CardBody} from "@nextui-org/card";
import {delay} from "framer-motion";
import {useLocation} from "react-router-dom";
import {DeleteIcon} from "@nextui-org/shared-icons";
import ToastUtil from "@/app/utils/toastUtil";
import ShareModifyService from "@/app/service/shareModifyService";
import DelNoteService from "@/app/service/components/delNoteService";
import DelShareService from "@/app/service/components/delShareService";
import {BsShareFill} from "react-icons/bs";
import {GoShare} from "react-icons/go";
import {SiCurl} from "react-icons/si";
import {PiShareNetworkBold} from "react-icons/pi";
import {RiShareFill} from "react-icons/ri";
import {HOST} from "@/app/constants/openApiConstants";

export default function Share() {
    //状态定义
    const location = useLocation();
    //加载中状态
    const [isLoading, setIsLoading] = useState(true);
    /*确认删除Modal状态*/
    const {isOpen: isOpenDelShare, onOpen: onOpenDelShare, onOpenChange: onOpenChangeDelShare} = useDisclosure();
    /*分享Id临存*/
    const [shareId, setShareId] = useState('');
    /*获取Host*/
    const [host, setHost] = useState('');
    /*SetHost*/
    useEffect(() => {
        if (typeof window !== 'undefined') {
            setHost(window.location.host)
        } else {
            setHost(HOST)
        }
    }, [])
    //获取分享数据
    let shareData = useAsyncList({
        async load({signal}) {
            try {
                const shareData = await ShareService();
                if (shareData !== undefined && shareData !== null && shareData.status) {
                    return {
                        items: shareData.data
                    }
                } else {
                    return {
                        items: [],
                    };
                }
            } catch (e) {
                throw new Error("出现未知错误，请刷新")
            }
        }
    });
    //创建一个消息管道，用于更新列表
    PubSub.unsubscribe('refreshShare');
    PubSub.subscribe('refreshShare', (_, data) => {
        shareData.reload();
    })
    //加载shareData
    useEffect(() => {
        async function initShare() {
            shareData.reload();
            delay(() => {
                setIsLoading(false);
            }, 100);
        }

        //初始化
        initShare().then(() => {
        });
        // eslint-disable-next-line
    }, [location]);
    return (
        <>
            {/*目录渲染*/}
            {
                //加载中状态判断
                isLoading ?
                    <Card className={'h-1/3'} shadow={"md"} radius={'lg'}>
                        <CardBody>
                            <div className={'flex justify-center flex-grow items-center bg-white p-5'}>
                                <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary"
                                         size={"sm"}/>
                            </div>
                        </CardBody>
                    </Card> :
                    shareData.items.length === 0 ?
                        DontExits('暂无分享的笔记哦 🧐') :
                        <Table
                            title={"我的分享"}
                            aria-label="我分享的所有笔记."
                            shadow={"sm"}/*阴影*/
                            hideHeader={false}/*隐藏头部*/
                            isStriped={false}/*条纹化*/
                            isHeaderSticky={true}/*头部阴影*/
                            fullWidth={true}
                        >
                            <TableHeader>
                                <TableColumn align={"center"} key="num">
                                    #
                                </TableColumn>
                                <TableColumn align={"center"} key="noteId">
                                    笔记名
                                </TableColumn>
                                <TableColumn align={"center"} key="endTime">
                                    截止时间
                                </TableColumn>
                                <TableColumn align={"center"} key="state">
                                    状态
                                </TableColumn>
                                <TableColumn align={"center"} key="setting">
                                    操作
                                </TableColumn>
                            </TableHeader>
                            {/*设置内容*/}
                            <TableBody
                                items={shareData.items}
                                isLoading={isLoading}
                                loadingContent={<Spinner label="加载中..."/>}
                            >
                                {(item: any) => (
                                    <TableRow key={item.id} className={"h-24"}>
                                        {(columnKey) =>
                                            <TableCell>{renderCell(item, columnKey)}</TableCell>
                                        }
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
            }
            {/*删除笔记*/}
            <DelShareService isOpenDelShare={isOpenDelShare} onOpenChangeDelShare={onOpenChangeDelShare}
                             shareId={shareId}/>
        </>)

    /*组件渲染*/
    function renderCell(item: any, columnKey: any) {
        const callValue = item[columnKey];
        switch (columnKey) {
            case 'num':
                return (
                    <Avatar isBordered color={item.type === 0 ? "default" : "primary"} radius={"lg"}
                            name={item.type === 0 ? "0" : "1"}/>
                );
            case 'noteId':
                return (<Chip className={'capitalize'} color={item.type === 0 ? "default" : "primary"} variant={"flat"}
                              size={'sm'}>&nbsp;{item.title}&nbsp;</Chip>);
            case 'endTime':
                return (<Chip className={item.type === 0 ? 'line-through' : ''}
                              color={item.type === 0 ? "default" : "primary"} variant="dot"
                              size={'sm'}>{item.endTime}</Chip>
                );
            case 'state':
                return (<Switch isSelected={item.type != 0} color="primary" size={"sm"} onValueChange={() => {
                    const serviceType = (item.type != 0) ? 0 : 1;
                    ShareModifyService(item.id, serviceType, 3).then(r => {/*处理返回结果*/
                    });
                }}/>);
            case 'setting':
                return (<div className={'flex items-center space-x-2'}>
                    <Tooltip color="success" content="复制链接">
              <span className="text-lg text-success cursor-pointer active:opacity-50" onClick={() => {
                  /*复制链接*/
                  copy(`http://${host}/view?shareId=${item.id}`);
                  ToastUtil("复制链接成功", '🍧', "success");
              }}>
                <RiShareFill/>
              </span>
                    </Tooltip>
                    <Tooltip color="danger" content="结束分享">
              <span className="text-lg text-danger cursor-pointer active:opacity-50" onClick={() => {
                  setShareId(item.id);
                  onOpenDelShare();
              }}>
                <DeleteIcon/>
              </span>
                    </Tooltip>
                </div>);
            default:
                return callValue;
        }
    }

    /*不存在的目录*/
    function DontExits(message: string) {
        return (
            <div>
                <Card className={'h-1/3'} shadow={"md"} radius={'lg'}>
                    <CardBody>
                        <div className={'flex justify-center flex-grow items-center bg-white p-5'}>
                            <Code color="warning"> {message} </Code>
                        </div>
                    </CardBody>
                </Card>
            </div>
        )
    }
}